<template>
  <div class="app-container">
    <el-card class="search-card">
      <el-form
        :model="queryParams"
        size="small"
        label-width="78px"
        ref="queryParams"
        class="formBox"
      >
        <el-row :gutter="0">
          <el-col :span="5">
            <el-form-item label="学校名称" prop="name">
              <el-input
                v-model="queryParams.name"
                placeholder="请输入学校名称"
                maxlength="50"
                show-word-limit
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="启用状态" prop="status">
              <el-select
                v-model="queryParams.status"
                placeholder="请选择启用状态"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dict.type.sys_open_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="handleQuery"
              >
                搜索
              </el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">
                重置
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card class="search-card">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['campus:school:add']"
            >新增</el-button
          >
        </el-col>
        <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>
    </el-card>
    <el-card class="table-card">
      <el-table v-loading="loading" :data="schoolList">
        <el-table-column label="学校名称" align="center" prop="name" />

        <el-table-column label="学校地区" align="center" prop="address">
          <template slot-scope="scope">
            <span>{{ scope.row.provinceName }}</span>
            <span>{{ scope.row.cityName }}</span>
            <span>{{ scope.row.areaName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="地址" align="center" prop="address" />
        <el-table-column label="联系人" align="center" prop="contactPerson" />
        <el-table-column label="联系电话" align="center" prop="contactPhone" />
        <el-table-column label="启用状态" align="center" prop="status">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.status == 1">启用</el-tag>
            <el-tag type="danger" v-if="scope.row.status == 0">停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="接入方式" align="center" prop="schoolPay">
          <template slot-scope="scope">
            <span v-if="scope.row.schoolPay == '1'">邮储H5</span>
            <span v-if="scope.row.schoolPay == '2'"> 支付宝小荷包</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createdAt, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="学校简介" align="center" prop="schoolIntro" /> -->
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['campus:school:edit']"
            >
              修改
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['campus:school:remove']"
              >删除
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-s-check"
              @click="authorization(scope.row)"
              v-hasPermi="['campus:school:authorization']"
              >授权
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改学校列表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" label-width="180px">
        <el-row>
          <el-col :span="20">
            <el-form-item label="学校名称" class="is-required">
              <el-input
                v-model="form.name"
                placeholder="请输入学校名称"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
            <el-form-item label="启用状态" prop="status" class="is-required">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_open_status"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item label="联系人" class="is-required">
              <el-input
                v-model="form.contactPerson"
                placeholder="请输入联系人"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
            <el-form-item label="联系电话" class="is-required">
              <el-input
                v-model="form.contactPhone"
                placeholder="请输入联系电话"
                maxlength="11"
                show-word-limit
              />
            </el-form-item>
            <el-form-item label="学校地区" class="is-required">
              <div class="width_100 display_flex">
                <el-select
                  v-model="form.provinceId"
                  @change="cityFun"
                  placeholder="请选择省"
                  style="flex: 1"
                >
                  <el-option
                    v-for="(item, index) in provinceList"
                    :key="index"
                    :value="item.code"
                    :label="item.name"
                  ></el-option>
                </el-select>
                <el-select
                  v-model="form.cityId"
                  @change="districtFun"
                  placeholder="请选择市"
                  style="flex: 1"
                >
                  <el-option
                    v-for="(item, index) in cityList"
                    :key="index"
                    :value="item.code"
                    :label="item.name"
                  ></el-option>
                </el-select>
                <el-select v-model="form.areaId" placeholder="请选择区" style="flex: 1">
                  <el-option
                    v-for="(item, index) in districtList"
                    :key="index"
                    :value="item.code"
                    :label="item.name"
                  ></el-option>
                </el-select>
              </div>
            </el-form-item>
            <el-form-item label="学校地址" class="is-required">
              <el-input
                v-model="form.address"
                type="textarea"
                placeholder="请输入地址"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
            <el-form-item label="学校简介" class="is-required">
              <el-input
                v-model="form.schoolIntro"
                type="textarea"
                placeholder="请输入内容"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
            <el-form-item label="接入方式" class="is-required">
              <el-select
                v-model="form.schoolPay"
                placeholder="请选择接入方式"
                class="width_100"
              >
                <el-option value="1" label="邮储H5"></el-option>
                <el-option value="2" label="支付宝小荷包"></el-option>
              </el-select>
            </el-form-item>
            <div v-if="form.schoolPay == '2'">
              <el-form-item label="学校内标" class="is-required">
                <el-input
                  v-model="form.schoolInCode"
                  placeholder="请输入学校内标"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
              <el-form-item label="学校外标" class="is-required">
                <el-input
                  v-model="form.schoolOutCode"
                  placeholder="请输入学校外标"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
              <el-form-item label="学校银行" class="is-required">
                <el-select
                  v-model="form.bankStatus"
                  placeholder="请选择学校银行"
                  class="width_100"
                >
                  <el-option value="BANK" label="指定银行"></el-option>
                  <el-option value="BANK_CARD" label="指定银行卡"></el-option>
                  <el-option value="BIN" label="指定银行卡BIN"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="银行选择" class="is-required">
                <el-select
                  v-model="form.bankId"
                  placeholder="请选择学校银行"
                  filterable
                  class="width_100"
                >
                  <el-option
                    v-for="(item, index) in getbankList"
                    :key="index"
                    :value="item.id"
                    :label="item.name"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                label="指定银行卡"
                class="is-required"
                v-if="form.bankStatus == 'BANK_CARD'"
              >
                <el-input
                  v-model="form.bankCode"
                  placeholder="请输入指定银行卡"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
              <el-form-item
                label="指定银行卡BIN"
                class="is-required"
                v-if="form.bankStatus == 'BIN'"
              >
                <el-input
                  v-model="form.bankCode"
                  placeholder="请输入指定银行卡BIN"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
            </div>
          </el-col>
        </el-row>

        <!-- <el-form-item label="学校logo" class="is-required">
          <image-upload v-model="form.schoolLogo" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- sss -->
    <el-dialog
      :title="title"
      :visible.sync="authorizationStatus"
      width="30%"
      append-to-body
    >
      <el-form ref="form" :model="form" label-width="180px">
        <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect">父子联动</el-checkbox>
        <el-tree
          :data="dataList"
          show-checkbox
          node-key="id"
          ref="tree"
          class="tree-border"
          style="height: 400px; overflow: auto"
          highlight-current
          :props="defaultProps"
          :check-strictly="!form.menuCheckStrictly"
        >
        </el-tree>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="treeSubmitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSchool,
  getSchool,
  delSchool,
  addSchool,
  updateSchool,
  getProvinceListFun,
  getCityListFun,
  getDistrictListFun,
  getbankFun,
  schoolAuth,
} from "@/api/campus/school";
import { getTenantId } from "@/utils/auth";
import { schoolMenuTreeselect } from "@/api/system/menu";
export default {
  name: "School",
  dicts: ["sys_open_status", "grade"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学校列表表格数据
      schoolList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        status: null,
      },
      // 表单参数
      form: {
        name: null,
        statuscontactPerson: null,
        contactPhone: null,
        provinceId: null,
        cityId: null,
        areaId: null,
        address: null,
        schoolIntro: null,
        schoolPay: null,
        schoolInCode: null,
        schoolOutCode: null,
        bankStatus: null,
        bankId: null,
        bankCode: null,
        menuCheckStrictly: true, // 父子联动控制
      },
      provinceList: [],
      cityList: [],
      districtList: [],
      // 银行
      getbankList: [],
      // 授权页面状态
      authorizationStatus: false,
      authorizationForm: {},
      defaultProps: {
        children: "children",
        label: "label",
      },
      dataList: [],
    };
  },
  created() {
    this.getList();
    this.provinceFun();
    this.getbankListFun();
  },
  methods: {
    /** 查询学校列表列表 */
    getList() {
      this.loading = true;
      listSchool(this.queryParams).then((response) => {
        this.schoolList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.authorizationStatus = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        statuscontactPerson: null,
        contactPhone: null,
        provinceId: null,
        cityId: null,
        areaId: null,
        address: null,
        schoolIntro: null,
        schoolPay: null,
        schoolInCode: null,
        schoolOutCode: null,
        bankStatus: null,
        bankId: null,
        bankCode: null,
        menuCheckStrictly: true, // 父子联动控制
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryParams");
      this.handleQuery();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加学校列表";
      this.form.status = "1";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getSchool(id).then((response) => {
        this.form = response.data;
        this.form.status = response.data.status + "";
        this.form.bankId = this.form.bankId * 1;
        this.cityFun(this.form.provinceId, "true");
        this.districtFun(this.form.cityId, "true");
        this.open = true;
        this.title = "修改学校列表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      var that = this;
      if (!this.form.name) {
        return that.$modal.msgError("请输入学校名称");
      }
      if (!this.form.status) {
        return that.$modal.msgError("请选择启用状态");
      }
      if (!this.form.contactPerson) {
        return that.$modal.msgError("请输入联系人");
      }
      if (!this.form.contactPhone) {
        return that.$modal.msgError("请输入联系电话");
      }
      if (!this.form.provinceId) {
        return that.$modal.msgError("请选择省");
      }
      if (!this.form.cityId) {
        return that.$modal.msgError("请选择市");
      }
      if (!this.form.areaId) {
        return that.$modal.msgError("请选择区");
      }
      if (!this.form.address) {
        return that.$modal.msgError("请输入学校地址");
      }
      if (!this.form.schoolIntro) {
        return that.$modal.msgError("请输入学校简介");
      }
      if (!this.form.schoolPay) {
        return that.$modal.msgError("请选择接入方式");
      }
      if (this.form.schoolPay == 2) {
        if (!this.form.schoolInCode) {
          return that.$modal.msgError("请输入学校内标");
        }
        if (!this.form.schoolOutCode) {
          return that.$modal.msgError("请输入学校外标");
        }
        if (!this.form.bankStatus) {
          return that.$modal.msgError("请选择学校银行");
        }
        if (!this.form.bankId) {
          return that.$modal.msgError("请选择银行");
        }
        if (this.form.bankStatus == "BANK_CARD") {
          return that.$modal.msgError("请输入指定银行卡");
        }
        if (this.form.bankStatus == "BIN") {
          return that.$modal.msgError("请输入指定银行卡BIN");
        }
      }
      this.$refs["form"].validate((valid) => {
        if (this.form.id != null) {
          updateSchool(this.form).then((response) => {
            that.$modal.msgSuccess("修改成功");
            that.open = false;
            that.getList();
          });
        } else {
          addSchool(that.form).then((response) => {
            that.$modal.msgSuccess("新增成功");
            that.open = false;
            that.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      this.$modal
        .confirm('是否确认删除学校列表编号为"' + ids + '"的数据项？')
        .then(function () {
          return delSchool(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "campus/school/export",
        {
          ...this.queryParams,
        },
        `school_${new Date().getTime()}.xlsx`
      );
    },
    provinceFun() {
      var that = this;
      getProvinceListFun().then((res) => {
        if (res.code == 200) {
          that.provinceList = res.data;
        }
      });
    },
    cityFun(options, status) {
      if (status == "true") {
        var that = this;
        getCityListFun({
          provinceCode: options,
        }).then((res) => {
          if (res.code == 200) {
            that.cityList = res.data;
          }
        });
      } else {
        this.form.cityId = "";
        this.form.areaId = "";
        var that = this;
        getCityListFun({
          provinceCode: options,
        }).then((res) => {
          if (res.code == 200) {
            that.cityList = res.data;
          }
        });
      }
    },
    districtFun(options, status) {
      var that = this;
      if (status != "true") {
        this.form.areaId = "";
      }
      getDistrictListFun({
        cityCode: options,
        provinceCode: this.form.provinceId,
      }).then((res) => {
        if (res.code == 200) {
          that.districtList = res.data;
        }
      });
    },
    getbankListFun() {
      var that = this;
      getbankFun().then((res) => {
        if (res.code == 200) {
          that.getbankList = res.data;
        } else {
        }
      });
    },
    authorization(options) {
      this.title = "学校授权";
      this.authorizationForm = options;
      schoolMenuTreeselect(options.id).then((res) => {
        this.dataList = res.data.menus;
        this.authorizationStatus = true;
        console.log(res.data.checkedKeys, "res.data.checkedKeys");
        this.$nextTick(() => {
          let checkedKeys = res.data.checkedKeys;
          checkedKeys.forEach((v) => {
            this.$nextTick(() => {
              this.$refs.tree.setChecked(v, true, false);
            });
          });
        });
      });
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value) {
      this.form.menuCheckStrictly = value ? true : false;
    },
    treeSubmitForm() {
      // 获取所有选中的菜单节点（包括半选中的父级菜单）
      let checkedKeys = this.$refs.tree.getCheckedKeys();
      let halfCheckedKeys = this.$refs.tree.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      
      if (checkedKeys.length == 0) {
        return this.$modal.msgError("请选择菜单");
      }

      schoolAuth({
        id: this.authorizationForm.id,
        menuIds: checkedKeys.join(","),
        tenantId: getTenantId(),
      }).then((res) => {
        this.authorizationStatus = false;
      });
    },
  },
};
</script>
<style>
.el-upload--picture-card {
  width: 90px !important;
  height: 90px !important;
  line-height: 90px !important;
}

.width_100 {
  width: 100% !important;
}
.display_flex {
  display: flex !important;
}
</style>
